<template>
  <a-tabs :active-key="activeKey" v-bind="$attrs" @change="onChange">
    <template v-for="item in renderArr" #[item]="scope">
      <slot :name="item" :scope="scope" v-bind="scope || {}"></slot>
    </template>
  </a-tabs>
</template>
<script>
import { getCurrentInstance, reactive, ref, toRefs, useSlots } from 'vue'
import { v4 } from 'uuid'
import { provide, inject } from 'vue'
export default {
  name: 'STabs',
  props: {
    defaultValue: {
      required: false
    }
  },
  emits: ['change'],
  expose: ['toggleTab', 'toggleTabToField', 'activeKey'],
  setup(props, context) {
    const slots = useSlots()
    const renderArr = Object.keys(slots)
    const data = reactive({
      renderArr
    })
    const { proxy } = getCurrentInstance()
    const id = v4()
    const activeKey = ref(props.defaultValue)
    let parent = proxy.$parent
    let registerHooks = []
    while (true) {
      if (!parent) {
        break
      }
      if (parent.$ && parent.$.type.name == 'SForm') {
        registerHooks.push(inject(parent.formRegisterHookName))
        break
      }
      parent = parent.$parent
    }
    const hooks = {}
    const hookName = 'tabHook_' + v4()
    provide(hookName, {
      register: (key, name) => {
        if (!hooks[key]) {
          hooks[key] = []
        }
        hooks[key].push(name)
      },
      unRegister: (key, name) => {
        let array = hooks[key]
        if (array.length > 0) {
          let index = array.indexOf(name)
          if (index >= 0) {
            array.splice(index, 1)
          }
        }
      }
    })
    context.expose({ tabHookName: hookName })
    if (registerHooks.length > 0) {
      registerHooks.forEach((hook) => {
        hook.register(id, proxy)
      })
    }

    return { fieldNames: hooks, activeKey, registerHooks, componentId: id, ...toRefs(data) }
  },
  beforeUnmount() {
    this.registerHooks.forEach((hook) => {
      hook.unRegister(this.componentId)
    })
  },
  methods: {
    onChange(e) {
      this.activeKey = e
      this.$emit('change', e)
    },
    toggleTab(key) {
      this.activeKey = key
    },
    toggleTabToField(name) {
      const keys = Object.keys(this.fieldNames)
      for (let index in keys) {
        const key = keys[index]
        const names = this.fieldNames[key]
        if (names.indexOf(name) >= 0) {
          this.activeKey = key
          break
        }
      }
    }
  }
}
</script>
